package com.cn.client;

import com.cn.common.MessageQueue;
import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * broker节点连接不上的 重试策略
 */
public class MqFaultStrategy {

    private MqFaultStrategyImpl mqFaultStrategy = new MqFaultStrategyImpl();
    private boolean sendLatencyFaultEnable = false;

    private long[] latencyMax = {50L, 100L, 550L, 1000L, 2000L, 3000L, 15000L};
    private long[] notAvailableDuration = {0L, 0L, 30000L, 60000L, 120000L, 180000L, 600000L};

    public MessageQueue selectMessageQueue(TopicPublishInfo topInfo, String brokerName) {
        if (this.sendLatencyFaultEnable) {
            int pos = topInfo.getThreadLocalIndex().getAndIncrement();
            if (pos < 0) {
                pos = 0;
            }
            for (int i = 0, size = topInfo.getMessageQueues().size(); i < size; i++) {
                int index = (pos++) % size;
                MessageQueue messageQueue = topInfo.getMessageQueues().get(index);
                if (null != messageQueue) {
                    if (this.mqFaultStrategy.isAvailable(messageQueue.getBrokerName())) {
                        if (StringUtils.isEmpty(brokerName) || !messageQueue.getBrokerName().equals(brokerName)) {
                            return messageQueue;
                        }
                    }
                }
            }


        } else {
            return topInfo.selectOneMessageQueue();
        }
        return null;
    }

    public boolean isSendLatencyFaultEnable() {
        return sendLatencyFaultEnable;
    }

    public void setSendLatencyFaultEnable(boolean sendLatencyFaultEnable) {
        this.sendLatencyFaultEnable = sendLatencyFaultEnable;
    }

    public static void main(String[] args) {
        ConcurrentMap<String, Integer> map = new ConcurrentHashMap<>();
        map.put("b", 10);
        map.put("a", 1);
        map.put("c", 21);

        for (Integer str : map.values()) {
            System.out.println(str);
        }
    }

}
